/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.seckill.common.listener;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.ProdType;
import com.yami.shop.bean.event.EsProductActivityInfoEvent;
import com.yami.shop.bean.order.EsProductOrder;
import com.yami.shop.bean.vo.search.ProductSearchVO;
import com.yami.shop.bean.vo.search.SeckillSearchVO;
import com.yami.shop.seckill.common.dao.SeckillMapper;
import com.yami.shop.seckill.common.model.Seckill;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 获取商品团购数据事件
 * @author yami
 */
@Component("seckillEsProductActivityInfoListener")
@AllArgsConstructor
public class EsProductActivityInfoListener {

    private final SeckillMapper seckillMapper;
    private final MapperFacade mapperFacade;

    @EventListener(EsProductActivityInfoEvent.class)
    @Order(EsProductOrder.SECKILL)
    public void seckillEsProductListener(EsProductActivityInfoEvent event) {
        List<ProductSearchVO> productList = event.getProductList();
        List<Long> ids = productList.stream()
                .filter(productSearchVO -> Objects.equals(productSearchVO.getProdType(), ProdType.PROD_TYPE_SECKILL.value()) &&
                        Objects.nonNull(productSearchVO.getActivityStartTime()))
                .map(ProductSearchVO::getActivityId).collect(Collectors.toList());
        // 没有秒杀商品需要处理
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        List<Seckill> seckillActivities = seckillMapper.selectList(new LambdaQueryWrapper<Seckill>().in(Seckill::getSeckillId, ids));
        Map<Long, Seckill> groupMap = seckillActivities.stream().collect(Collectors.toMap(Seckill::getSeckillId, s -> s));
        for (ProductSearchVO productSearchVO : productList) {
            Seckill seckill = groupMap.get(productSearchVO.getActivityId());
            if (Objects.isNull(seckill)) {
                continue;
            }
            productSearchVO.setActivityInProgress(Boolean.TRUE);
            SeckillSearchVO seckillSearchVO = mapperFacade.map(seckill, SeckillSearchVO.class);
            productSearchVO.setSeckillSearchVO(seckillSearchVO);
        }
    }

}
